package com.amadeus.personal_demo;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ActionMenuView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;

import com.google.zxing.WriterException;
import com.gprinter.command.EscCommand;
import com.gprinter.command.LabelCommand;
import com.gprinter.command.EscCommand.ENABLE;

import org.w3c.dom.Text;

import java.sql.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static android.hardware.usb.UsbManager.ACTION_USB_DEVICE_DETACHED;
import static com.amadeus.personal_demo.Constant.ACTION_USB_PERMISSION;
import static com.amadeus.personal_demo.Constant.CONN_STATE_DISCONN;
import static com.amadeus.personal_demo.Constant.MESSAGE_UPDATE_PARAMETER;
import static com.amadeus.personal_demo.Constant.USB_REQUEST_CODE;
import static com.amadeus.personal_demo.DeviceConnFactoryManager.ACTION_QUERY_PRINTER_STATE;
import static com.amadeus.personal_demo.DeviceConnFactoryManager.CONN_STATE_FAILED;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    ArrayList<String> per = new ArrayList<>();
    private UsbManager usbManager;

    //电子秤端口
    H711ReadThread h711ReadThread;

    //扫描枪
    QRReadThread qrReadThread;

    TextView txtWeigh;
    ImageView qrCode;
    ImageView d128Code;
    TextView txtPiWeigh;
    TextView txtZuzhi;
    EditText edtZuzhi;
    EditText edtTotalWeight;
    TextView txtYeti;

    //倍数
    private byte mBeishu;
    //状态
    private byte mChouyeStatus=Constants.STATUS_IDLE;
    //重量
    private Float mWeightBeizi;
    private Float mWeightZuzhi;
    private Float mWeightTotal;

    private volatile static MainActivity INSTANCE = null;

    private int counts;
    private static final int REQUEST_CODE = 0x004;

    //连接状态断开
    private static final int CONN_STATE_DISCONN = 0x007;
    //使用打印机指令错误
    private static final int PRINTER_COMMAND_ERROR = 0x008;
    //ESC查询打印机实时状态指令
    private byte[] esc = {0x10, 0x04, 0x02};
    //TSC查询打印机状态指令
    private byte[] tsc = {0x1b, '!', '?'};

    private static final int CONN_MOST_DEVICES = 0x11;
    private static final int CONN_PRINTER = 0x12;
    private PendingIntent mPermissionIntent;
    private String[] permissions = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH
    };
    private String usbName;
    private TextView tvConnState;
    private ThreadPool threadPool;
    //判断打印机所使用的指令是否是ESC
    private int id = 0;
    private EditText etPrintCounts;
    private View sview;

    private String Names;
    private String Bing;
    private String bed;
    private String ation;
    private String Sex;
    private String ages;
    private String biaob;
    private String Dept;
    private String Depts;
    private String B_weight;
    private String Count_weight;
    private String Doctors;
    private String Date;

    private EditText ed_name;
    private EditText ed_bingqu;
    private EditText ed_bed;
    private EditText ed_age;
    private EditText ed_biaob;
    private EditText doctors;
    private EditText b_weight;
    private EditText count_weight;
    private EditText date;
    private Spinner sp_sex;
    private Spinner sp_dept;
    private Spinner sp_depts;
    private Toolbar toolbar;
    private TextView work_state;
    private String mdata;

    //以上均常量
    private void InitViews(){
        txtWeigh = (TextView)findViewById(R.id.weight_data);
        qrCode = (ImageView)findViewById(R.id.qr_code);
        d128Code = (ImageView)findViewById(R.id.d128_code);
        txtPiWeigh = (TextView)findViewById(R.id.tare_data);
        txtZuzhi = (TextView)findViewById(R.id.tissue_data);
        txtYeti = (TextView)findViewById(R.id.humor_data);
        work_state = (TextView)findViewById(R.id.work_state);
        //edtZuzhi = (EditText)findViewById(R.id.)
    }
    private void editlist(){
        ed_name = (EditText) findViewById(R.id.edit_name);
        ed_bingqu = (EditText)findViewById(R.id.edit_ward) ;
        ed_bed = (EditText)findViewById(R.id.edit_bed);
        ed_age = (EditText)findViewById(R.id.edit_year);
        ed_biaob = (EditText)findViewById(R.id.edit_specimen);
        b_weight = (EditText) findViewById(R.id.edit_weights);
        doctors = (EditText) findViewById(R.id.edit_doctors);
        count_weight = (EditText)findViewById(R.id.count_weight_date);
        date = (EditText)findViewById(R.id.edit_date);
    }
    private void clearedit(){
        ed_name.setText("");
        ed_bingqu.setText("");
        ed_bed.setText("");
        ed_age.setText("");
        ed_biaob.setText("");
        b_weight.setText("");
        doctors.setText("");
        count_weight.setText("");
        date.setText("");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setLang();
        toolbar = (Toolbar)findViewById(R.id.toolbars);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        Log.e(TAG,"onCreate");
        INSTANCE = this;
        InitViews();
        editlist();
        tvConnState = (TextView)findViewById(R.id.printer_state);

        sp_sex = (Spinner)findViewById(R.id.edit_sex);
        sp_dept = (Spinner) findViewById(R.id.department_sp);
        Spinner sp_weight = (Spinner) findViewById(R.id.multiple_data);
        sp_depts = (Spinner)findViewById(R.id.department_sps);

        //Button setting = (Button)findViewById(R.id.setting);
        final Button printers = (Button)findViewById(R.id.printers);
        ImageView qr_code = (ImageView)findViewById(R.id.qr_code);
        ImageView d128_code = (ImageView)findViewById(R.id.d128_code);
        usbManager = (UsbManager)getSystemService(Context.USB_SERVICE);

        //此处出发权限检查,不要忘记加权限
        checkPermission();
        requestPermisstion();
        /*setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Settings.class);
                startActivity(intent);
            }
        });*/
        ub();

        //设置APP二维码与一维码
        /*try {
            Bitmap qr_codes = QRCode.createCode("这里可以外部获取",200);
            Bitmap d128_codes = D128_code.createCode("6928804010190",400);
            qr_code.setImageBitmap(qr_codes);
            d128_code.setImageBitmap(d128_codes);
        } catch (WriterException e) {
            e.printStackTrace();
        }*/


        //启动读(得要硬件调试)
        /*h711ReadThread = new H711ReadThread();
        h711ReadThread.start();

        qrReadThread = new QRReadThread();
        qrReadThread.start();*/

        printers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnLabelPrint(v);
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.add_printer:
                    btnUsbConn();
                break;
            case R.id.language_switch:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.toptitle);
                builder.setMessage(R.string.message);
                builder.setCancelable(false);
                builder.setPositiveButton(R.string.yes,new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Locale getlocale = LanguageUtil.getAppLocale(App.getContext());
                        //String getApplocale = LanguageUtil.getAppLanguage(App.getContext());
                        //LanguageUtil.changeAppLanguage(App.getContext(),getlocale,true);
                        changeAppLanguage();
                    }
                });

                builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.show();
                break;
            case R.id.check:
                AlertDialog.Builder builders = new AlertDialog.Builder(this);
                builders.setTitle(R.string.check_top);
                builders.setMessage(R.string.chenck_msg);
                builders.setCancelable(false);
                builders.setPositiveButton(R.string.put,new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

                builders.setNegativeButton(R.string.out, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builders.show();
                break;
            default:
        }
        return true;
    }

    protected void onStart(){
        super.onStart();
        Log.e(TAG,"onStart");
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(ACTION_USB_DEVICE_DETACHED);
        filter.addAction(ACTION_QUERY_PRINTER_STATE);
        filter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE);
        registerReceiver(receiver,filter);

    }

    protected void onRestart(){
        super.onRestart();
        Log.e(TAG,"onRestart");
    }

    protected void onResume(){
        super.onResume();
        Log.e(TAG,"onResume");
    }

    private void checkPermission(){
        for(String permission : permissions){
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this,permission)){
                per.add(permission);
            }
        }
    }

    private void requestPermisstion(){
        if (per.size() >0){
            String[] p = new String[per.size()];
            ActivityCompat.requestPermissions(this,per.toArray(p),REQUEST_CODE);
        }
    }

    public void btnUsbConn(){
        //USB连接方式
        startActivityForResult(new Intent(this,UsbDeviceList.class), Constant.USB_REQUEST_CODE);
    }

    //标签打印功能
    public void btnLabelPrint(View view) {
        threadPool = ThreadPool.getInstantiation();
        threadPool.addTask(new Runnable() {
            @Override
            public void run() {
                if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] == null || !DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getConnState()) {
                    mHandler.obtainMessage(CONN_PRINTER).sendToTarget();
                    return;
                }
                if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getCurrentPrintCommand() == PrintCommand.TSC) {
                    sendLabel();
                } else {
                    mHandler.obtainMessage(PRINTER_COMMAND_ERROR).sendToTarget();
                }
            }
        });
    }

    public void btnDisConn(View view){
        mHandler.obtainMessage(CONN_STATE_DISCONN).sendToTarget();
    }

    //USB连接
    public void usbConn(UsbDevice usbDevice){
        new DeviceConnFactoryManager.Build()
                .setId(id)
                .setConnMethod(DeviceConnFactoryManager.CONN_METHOD.USB)
                .setUsbDevice(usbDevice)
                .setContext(this)
                .build();
        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].openPort();
    }

    public void btnReceiptPrint(View view){
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] == null || !DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getConnState()){
            Utils.toast(this,getString(R.string.str_cann_printer));
            return;
        }
        threadPool = ThreadPool.getInstantiation();
        threadPool.addTask(new Runnable() {
            @Override
            public void run() {
                if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getCurrentPrintCommand() == PrintCommand.ESC){
                    sendReceiptWithResponse();
                }else {
                    mHandler.obtainMessage(PRINTER_COMMAND_ERROR).sendToTarget();
                }
            }
        });
    }

    //发送连续打印命令
    private void sendContinuityPrint(){
        ThreadPool.getInstantiation().addTask(new Runnable() {
            @Override
            public void run() {
                if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null && DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getConnState()){
                    ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder("MainActivity_sendContinyity_Timer");
                    ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1,threadFactoryBuilder);
                    scheduledExecutorService.schedule(threadFactoryBuilder.newThread(new Runnable() {
                        @Override
                        public void run() {
                            counts--;
                            if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].getCurrentPrintCommand() == PrintCommand.ESC){
                                sendReceiptWithResponse();
                            }else {
                                sendLabel();
                            }
                        }
                    }),1000, TimeUnit.MILLISECONDS);
                }
            }
        });
    }

    protected void onActivityResult(int requestCode,int resultCode,Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case Constant.USB_REQUEST_CODE:{
                    usbName = data.getStringExtra(UsbDeviceList.USB_NAME);
                    UsbDevice usbDevice = Utils.getUsbDeviceFromName(MainActivity.this,usbName);
                    if (usbManager.hasPermission(usbDevice)){
                        usbConn(usbDevice);
                    }else {
                        mPermissionIntent = PendingIntent.getBroadcast(this,0,new Intent(ACTION_USB_PERMISSION),0);
                        usbManager.requestPermission(usbDevice,mPermissionIntent);
                    }
                    break;
                }
                default:
                    break;
            }
        }
    }


    //发送标签打印内容
    void sendLabel(){
        // String get_datas = get_data.getText().toString();
        LabelCommand tsc = new LabelCommand();
        // 设置标签尺寸，按照实际尺寸设置
        tsc.addSize(40, 60);
        // 设置标签间隙，按照实际尺寸设置，如果为无间隙纸则设置为0
        tsc.addGap(1);
        // 设置打印方
        tsc.addOffset(3);
        tsc.addDirection(LabelCommand.DIRECTION.FORWARD, LabelCommand.MIRROR.NORMAL);
        // 开启带Response的打印，用于连续打印
        tsc.addQueryPrinterStatus(LabelCommand.RESPONSE_MODE.OFF);
        // 设置原点坐标
        tsc.addReference(0, 0);
        // 撕纸模式开启
        tsc.addTear(EscCommand.ENABLE.ON);
        // 清除打印缓冲区
        tsc.addCls();
        // 绘制简体中文
        tsc.addText(310,2,LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,LabelCommand.ROTATION.ROTATION_90,LabelCommand.FONTMUL.MUL_1,LabelCommand.FONTMUL.MUL_1,Names = "姓名:"+ed_name.getText().toString()+" 性别:"+(String)sp_sex.getSelectedItem()+" 年龄:"+ed_age.getText().toString());
        tsc.addText(270,2,LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,LabelCommand.ROTATION.ROTATION_90,LabelCommand.FONTMUL.MUL_1,LabelCommand.FONTMUL.MUL_1,Bing = "病区:"+ed_bingqu.getText().toString()+" 病床:"+ed_bed.getText().toString());
        tsc.addText(230,2,LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,LabelCommand.ROTATION.ROTATION_90,LabelCommand.FONTMUL.MUL_1,LabelCommand.FONTMUL.MUL_1,biaob = "送检标本:"+ed_biaob.getText().toString());
        tsc.addText(190,2,LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,LabelCommand.ROTATION.ROTATION_90,LabelCommand.FONTMUL.MUL_1,LabelCommand.FONTMUL.MUL_1,Dept = "送检科室:"+(String)sp_dept.getSelectedItem()+" "+sp_depts.getSelectedItem());
        tsc.addText(150,2,LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,LabelCommand.ROTATION.ROTATION_90,LabelCommand.FONTMUL.MUL_1,LabelCommand.FONTMUL.MUL_1,B_weight = "标本重量:"+b_weight.getText().toString()+" 总重量:"+count_weight.getText().toString());
        tsc.addText(110,2,LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,LabelCommand.ROTATION.ROTATION_90,LabelCommand.FONTMUL.MUL_1,LabelCommand.FONTMUL.MUL_1,Doctors = "送检医生:"+doctors.getText().toString()+" 送检日期:"+date.getText().toString());

        //tsc.addText(310,145,LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,LabelCommand.ROTATION.ROTATION_90,LabelCommand.FONTMUL.MUL_1,LabelCommand.FONTMUL.MUL_1,Sex = "性别:"+(String)sp_sex.getSelectedItem());
        //tsc.addText(270,160,LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,LabelCommand.ROTATION.ROTATION_90,LabelCommand.FONTMUL.MUL_1,LabelCommand.FONTMUL.MUL_1,bed = "病床:"+ed_bed.getText().toString());
        //tsc.addText(150,190,LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,LabelCommand.ROTATION.ROTATION_90,LabelCommand.FONTMUL.MUL_1,LabelCommand.FONTMUL.MUL_1,Count_weight = "总重量:"+count_weight.getText().toString());
        //tsc.addText(110,190,LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,LabelCommand.ROTATION.ROTATION_90,LabelCommand.FONTMUL.MUL_1,LabelCommand.FONTMUL.MUL_1,Date = "送检日期:"+date.getText().toString());

        //tsc.addText(310,255,LabelCommand.FONTTYPE.SIMPLIFIED_CHINESE,LabelCommand.ROTATION.ROTATION_90,LabelCommand.FONTMUL.MUL_1,LabelCommand.FONTMUL.MUL_1,ages = "年龄:"+ed_age.getText().toString());

        // 绘制图片
        //Bitmap b = BitmapFactory.decodeResource(getResources(), R.mipmap.gprinter);
        //tsc.addBitmap(20, 50, LabelCommand.BITMAP_MODE.OVERWRITE, b.getWidth(), b);
        //绘制二维码
        tsc.addQRCode(280, 315, LabelCommand.EEC.LEVEL_L, 6, LabelCommand.ROTATION.ROTATION_90,mdata);
        // 绘制一维条码
        tsc.add1DBarcode(70, 150, LabelCommand.BARCODETYPE.CODE128, 50, LabelCommand.READABEL.EANBEL, LabelCommand.ROTATION.ROTATION_90, mdata);
        // 打印标签
        tsc.addPrint(1, 1);
        // 打印标签后 蜂鸣器响

        tsc.addSound(2, 100);
        tsc.addCashdrwer(LabelCommand.FOOT.F5, 255, 255);
        Vector<Byte> datas = tsc.getCommand();

        // 绘制图片
        /*Bitmap b = BitmapFactory.decodeResource(getResources(), R.mipmap.gprinter);
        tsc.addBitmap(20, 50, LabelCommand.BITMAP_MODE.OVERWRITE, b.getWidth(), b);

        tsc.addQRCode(250, 80, LabelCommand.EEC.LEVEL_L, 5, LabelCommand.ROTATION.ROTATION_0, " www.smarnet.cc");
        // 绘制一维条码
        tsc.add1DBarcode(20, 250, LabelCommand.BARCODETYPE.CODE128, 100, LabelCommand.READABEL.EANBEL, LabelCommand.ROTATION.ROTATION_0, "SMARNET");
        // 打印标签
        tsc.addPrint(1, 1);
        // 打印标签后 蜂鸣器响

        tsc.addSound(2, 100);
        tsc.addCashdrwer(LabelCommand.FOOT.F5, 255, 255);
        Vector<Byte> datas = tsc.getCommand();*/
        // 发送数据
        if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] == null) {
            return;
        }
        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(datas);
        tsc.addPrint(1,1);

    }

    //发送票据打印内容
    void sendReceiptWithResponse(){
        EscCommand esc = new EscCommand();
        esc.addInitializePrinter();
        esc.addPrintAndFeedLines((byte) 3);
        // 设置打印居中
        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
        // 设置为倍高倍宽
        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF);
        // 打印文字
        esc.addText("Sample\n");
        esc.addPrintAndLineFeed();

        /* 打印文字 */
        // 取消倍高倍宽
        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);
        // 设置打印左对齐
        esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);
        // 打印文字
        esc.addText("Print text\n");
        // 打印文字
        esc.addText("Welcome to use SMARNET printer!\n");

        /* 打印繁体中文 需要打印机支持繁体字库 */
        String message = "佳博智匯票據打印機\n";
        esc.addText(message, "GB2312");
        esc.addPrintAndLineFeed();

        /* 绝对位置 具体详细信息请查看GP58编程手册 */
        esc.addText("智汇");
        esc.addSetHorAndVerMotionUnits((byte) 7, (byte) 0);
        esc.addSetAbsolutePrintPosition((short) 6);
        esc.addText("网络");
        esc.addSetAbsolutePrintPosition((short) 10);
        esc.addText("设备");
        esc.addPrintAndLineFeed();

        /* 打印图片 */
        // 打印文字
        esc.addText("Print bitmap!\n");
        Bitmap b = BitmapFactory.decodeResource(getResources(),
                R.mipmap.gprinter);
        // 打印图片
        esc.addOriginRastBitImage(b, 384, 0);

        /* 打印一维条码 */
        // 打印文字
        esc.addText("Print code128\n");
        esc.addSelectPrintingPositionForHRICharacters(EscCommand.HRI_POSITION.BELOW);
        // 设置条码可识别字符位置在条码下方
        // 设置条码高度为60点
        esc.addSetBarcodeHeight((byte) 60);
        // 设置条码单元宽度为1
        esc.addSetBarcodeWidth((byte) 1);
        // 打印Code128码
        esc.addCODE128(esc.genCodeB("SMARNET"));
        esc.addPrintAndLineFeed();

        /*
         * QRCode命令打印 此命令只在支持QRCode命令打印的机型才能使用。 在不支持二维码指令打印的机型上，则需要发送二维条码图片
         */
        // 打印文字
        esc.addText("Print QRcode\n");
        // 设置纠错等级
        esc.addSelectErrorCorrectionLevelForQRCode((byte) 0x31);
        // 设置qrcode模块大小
        esc.addSelectSizeOfModuleForQRCode((byte) 3);
        // 设置qrcode内容
        esc.addStoreQRCodeData("www.smarnet.cc");
        esc.addPrintQRCode();// 打印QRCode
        esc.addPrintAndLineFeed();

        // 设置打印左对齐
        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);
        //打印文字
        esc.addText("Completed!\r\n");

        // 开钱箱
        esc.addGeneratePlus(LabelCommand.FOOT.F5, (byte) 255, (byte) 255);
        esc.addPrintAndFeedLines((byte) 8);
        // 加入查询打印机状态，打印完成后，此时会接收到GpCom.ACTION_DEVICE_STATUS广播
        esc.addQueryPrinterStatus();
        Vector<Byte> datas = esc.getCommand();
        // 发送数据
        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].sendDataImmediately(datas);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action){
                case ACTION_USB_PERMISSION:
                    synchronized (this) {
                        UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            if (device != null) {
                                System.out.println("permission ok for device" + device);
                                usbConn(device);
                            }
                        } else {
                            System.out.println("permission deined for device" + device);
                        }
                    }
                    break;
                case ACTION_USB_DEVICE_DETACHED:
                case DeviceConnFactoryManager.ACTION_CONN_STATE:
                    int state = intent.getIntExtra(DeviceConnFactoryManager.STATE,-1);
                    int deviceId = intent.getIntExtra(DeviceConnFactoryManager.DEVICE_ID,-1);
                    switch (state){
                        case DeviceConnFactoryManager.CONN_STATE_DISCONNECT:
                            if (id == deviceId){
                                tvConnState.setText(getString(R.string.str_conn_state_disconnect));
                            }
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTING:
                            tvConnState.setText(getString(R.string.str_conn_state_connecting));
                            break;
                        case DeviceConnFactoryManager.CONN_STATE_CONNECTED:
                            tvConnState.setText(getString(R.string.str_conn_state_connected) + "\n" + getConnDeviceInfo());
                            break;
                        case CONN_STATE_FAILED:
                            Utils.toast(MainActivity.this,getString(R.string.str_conn_fail));
                            tvConnState.setText(getString(R.string.str_conn_state_disconnect));
                            break;
                        default:
                            break;
                    }
                    break;
                case ACTION_QUERY_PRINTER_STATE:
                    if (counts > 0){
                        sendContinuityPrint();
                    }
            }

        }
    };

    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what){
                case CONN_STATE_DISCONN:
                    if (DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id] != null){
                        DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id].closePort(id);
                    }
                    break;
                case PRINTER_COMMAND_ERROR:
                    Utils.toast(MainActivity.this,getString(R.string.str_choice_printer_command));
                    break;
                case CONN_PRINTER:
                    Utils.toast(MainActivity.this,getString(R.string.str_cann_printer));
                    break;
                default:
                    break;
            }
        }
    };

    protected void onStop(){
        super.onStop();
        Log.e(TAG,"onStop");
        unregisterReceiver(receiver);

    }

    protected void onDestroy(){
        super.onDestroy();
        Log.e(TAG,"onDestory");
        DeviceConnFactoryManager.closeALLPort();
        if (threadPool != null){
            threadPool.stopThreadPool();
        }
    }

    private String getConnDeviceInfo(){
        String str = "";
        DeviceConnFactoryManager deviceConnFactoryManager = DeviceConnFactoryManager.getDeviceConnFactoryManagers()[id];
        if (deviceConnFactoryManager != null && deviceConnFactoryManager.getConnState()){
            if ("USB".equals(deviceConnFactoryManager.getConnMethod().toString())){
                str += "USB\n";
                str += "USB Name:" + deviceConnFactoryManager.usbDevice().getDeviceName();
            }
        }
        return str;
    }


    //中英文切换

    public void setLocale(Locale mlocale){
        Resources resources = getResources();
        DisplayMetrics ms = resources.getDisplayMetrics();
        Configuration configuration = resources.getConfiguration();

        configuration.locale = mlocale;
        resources.updateConfiguration(configuration,ms);
        LanguageUtil.saveLanguageSetting(App.getContext(),mlocale);
    }

    public void changess(View view){
        changeAppLanguage();
    }
    public void changeAppLanguage(){
        String lang = LanguageUtil.getAppLanguage(App.getContext());
        if (lang.equals("en")){
            setLocale(Locale.SIMPLIFIED_CHINESE);
        }else if (lang.equals("zh")){
            setLocale(Locale.US);
        }
        recreate();
    }

    public void setLang(){
        Locale language = LanguageUtil.getAppLocale(App.getContext());
        if (language.equals("zh")){
            setLocale(Locale.SIMPLIFIED_CHINESE);
        }else if (language.equals("en")){
            setLocale(Locale.US);
        }
    }

    public void ub(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                UsbManager manager = (UsbManager)getSystemService(Context.USB_SERVICE);
                //获取设备列表信息
                HashMap<String, UsbDevice> devices = manager.getDeviceList();
                Iterator<UsbDevice> deviceIterator = devices.values().iterator();

                int count = devices.size();
                if (count > 0) {
                    while (deviceIterator.hasNext()) {
                        UsbDevice device = deviceIterator.next();
                        String devicename = device.getDeviceName();
                        usbName = devicename;//data.getStringExtra(UsbDeviceList.USB_NAME);
                        UsbDevice usbDevice = Utils.getUsbDeviceFromName(MainActivity.this,usbName);
                        if (usbManager.hasPermission(usbDevice)){
                            usbConn(usbDevice);
                        }else {
                            //mPermissionIntent = PendingIntent.getBroadcast(this,0,new Intent(ACTION_USB_PERMISSION),0);
                            //usbManager.requestPermission(usbDevice,mPermissionIntent);
                        }
                    }
                }
            }

        });
    }

    //
    public void MssPro(final  Byte[] msg,int len) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (msg[3] == Constants.COM_UPWEIGHT) {//上传
                    byte[] bw = new byte[4];
                    bw[0] = msg[8];
                    bw[1] = msg[7];
                    bw[2] = msg[6];
                    bw[3] = msg[5];
                    int iw = Constants.byte2Int(bw);
                    float w1 = iw;
                    w1 = w1 /10;
                    Float w = Float.valueOf(w1);
                    switch (msg[4]){
                        case Constants.WEIGHT_NORMAL:
                            if (txtWeigh != null) {
                                txtWeigh.setText(w.toString());
                                work_state.setText(R.string.work_draw);
                            }
                            if((mChouyeStatus==Constants.STATUS_ATUOOVER)||(mChouyeStatus==Constants.STATUS_AUTO)){
                                if(txtYeti != null){
                                    Float Y = w - mWeightBeizi - mWeightZuzhi;
                                    txtYeti.setText(Y.toString());
                                    if(mChouyeStatus==Constants.STATUS_ATUOOVER){
                                        mChouyeStatus = Constants.STATUS_IDLE;
                                    }
                                }
                            }

                            break;
                        case Constants.WEIGHT_BEIZI:
                            mWeightBeizi = w;
                            if(txtPiWeigh!=null){
                                txtPiWeigh.setText(mWeightBeizi.toString());
                                txtZuzhi.setText("--");
                                txtYeti.setText("--");
                            }
                            break;
                        case Constants.WEIGHT_ZUZHI:
                            mWeightZuzhi = w - mWeightBeizi;
                            mChouyeStatus=Constants.STATUS_AUTO;
                            if(txtZuzhi!=null){
                                txtZuzhi.setText(mWeightZuzhi.toString());
                                txtYeti.setText("--");
                            }
                            mBeishu = 5;
                            h711ReadThread.SendData(Constants.COM_GETWEIGHTACK,mBeishu);
                            break;
                    }
                }else if(msg[3]==Constants.COM_KEYPRINT){

                }else if(msg[3]==Constants.COM_STATUS){
                    switch (msg[4]) {
                        case Constants.COM_STATUS_AUTOOVER:
                            mChouyeStatus = Constants.STATUS_ATUOOVER;
                            break;
                    }
                }
            }
        });
    }

    public void QRPro(final  Byte type, final String data) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(type == 'q'|| type == 'D') {
                    Bitmap q = null;
                    Bitmap D = null;
                    try {
                        q = QRCode.createCode(data, 200);
                        D = D128_code.createCode(data, 400);
                        qrCode.setImageBitmap(q);
                        d128Code.setImageBitmap(D);
                    } catch (WriterException e) {
                        e.printStackTrace();
                    }
                }/*else if(type == 'D'){
                    Bitmap q = null;
                    try {


                    } catch (WriterException e) {
                        e.printStackTrace();
                    }
                }*/
                mdata = data;
                clearedit();
            }
        });
    }

    static public MainActivity getInstance(){
        return INSTANCE;
    }
}
